package com.meitianhui.convenitenbuy.main.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.contract.MainContract;
import com.meitianhui.convenitenbuy.main.di.DaggerMainComponent;
import com.meitianhui.convenitenbuy.main.di.MainModule;
import com.meitianhui.convenitenbuy.main.model.bean.CollectedStores;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.model.bean.UpdateBean;
import com.meitianhui.convenitenbuy.main.model.bean.VersionInfo;
import com.meitianhui.convenitenbuy.main.model.event.ExitEvent;
import com.meitianhui.convenitenbuy.main.presenter.MainPresenter;
import com.meitianhui.convenitenbuy.module.home.model.bean.BannerBean;
import com.meitianhui.convenitenbuy.module.home.ui.HomeFragment;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.AdWebViewActivity;
import com.meitianhui.convenitenbuy.module.mine.model.LogOutBean;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.CollectStoreEventBean;
import com.meitianhui.convenitenbuy.module.mine.ui.fragment.MineFragment;
import com.meitianhui.convenitenbuy.module.order.ui.fragment.OrderFragment;
import com.meitianhui.convenitenbuy.module.store.ui.StoreFragment;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.ui.WalletFragment;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletChangeActivity;
import com.meitianhui.convenitenbuy.service.UpdateService;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxTimerUtils;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.UpdateDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.socialize.UMShareAPI;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.meitianhui.convenitenbuy.Constants.EXIT_HYPHENATE_EVENT;
import static com.meitianhui.convenitenbuy.util.JumpUtil.INTENT_FLAG_SOURCE;

public class MainActivity extends BaseActivity
        implements MainContract.View, RadioGroup.OnCheckedChangeListener {

    private static final String CURRENT_FRAGMENT_TAG_WALLET = "CURRENT_FRAGMENT_TAG_WALLET";
    private static final String CURRENT_FRAGMENT_TAG_ORDER = "CURRENT_FRAGMENT_TAG_ORDER";
    public static final String CURRENT_FRAGMENT_TAG_MINE = "CURRENT_FRAGMENT_TAG_MINE";
    private static final String CURRENT_FRAGMENT_TAG_STORE = "CURRENT_FRAGMENT_TAG_STORE";
    private HomeFragment mHomeFragment;
    private RadioGroup rgHome;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private String fragmentTag = "";
    private Boolean isExit = false;
    private UpdateDialog mDialog;
    private ImageView mIvPic;
    private RxPermissions mRxPermissions;
    @Inject
    MainPresenter presenter;


    private String mRedMsg = null;
    private boolean isSetUpRedPacket;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTranslucentStatus(R.color.transparent);
        setContentView(R.layout.activity_main);
        rgHome = getViewById(R.id.rg_home);
        mIvPic = getViewById(R.id.iv_pic);

        RxUtils.bindEvents(getViewById(R.id.ll_ad), this);
        boolean haveNavigation = SystemUtils.checkDeviceHasNavigationBar(this);
        if (haveNavigation) {
            SystemUtils.assistActivity(findViewById(android.R.id.content));
           // rgHome.setPadding(rgHome.getPaddingLeft(), rgHome.getPaddingTop(), rgHome.getPaddingRight(), getNavigationBarHeight());
           // rgHome.getLayoutParams().height = getNavigationBarHeight() + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, App.getInstance().getResources().getDisplayMetrics());
        }

        rgHome.setOnCheckedChangeListener(this);
        DaggerMainComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
        initFragmentManager();
        registerEvent();
        presenter.getAd();
        // Both getVersion() and getUpdateInfo() are being used.
        // so do NOT use them at the same time.
        presenter.getVersion();
        presenter.getUpdateInfo();
    }

    private int getNavigationBarHeight() {
        Resources resources = this.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    private void initFragmentManager() {
        Disposable logoutDisposable = RxBus.get().toFlowable(LogOutBean.class).subscribe(new Consumer<LogOutBean>() {
            @Override
            public void accept(LogOutBean logOutBean) throws Exception {
                if (logOutBean.logOut.equals("logout")) {
                    ((RadioButton) findViewById(R.id.rb_home)).setChecked(true);
                    onCheckedChanged(rgHome, R.id.rb_home);
                }
            }
        });
        mCompositeDisposable.add(logoutDisposable);
        fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        mHomeFragment = new HomeFragment();
        transaction.replace(R.id.content, mHomeFragment, HomeFragment.Tag);
        fragmentTag = HomeFragment.Tag;
        transaction.addToBackStack(null);
        transaction.commit();
        if (InfoProvider.getLoginStatus(this) && InfoProvider.getUserToken(App.getInstance()) != null) {
            presenter.getDefaultStores();
        }
    }

    /**
     * 如果登录成功那么跳到fragment界面
     */
    private Fragment jumpToFragment(String strTag, int id) {
        Fragment fragment = fragmentManager.findFragmentByTag(strTag);
        fragmentTag = strTag;
        if (fragment != null) {
        } else {
            if(id == R.id.rb_home){
                fragment = new HomeFragment();
            }else if (id == R.id.rb_mine) {
                fragment = new MineFragment();
            } else if (id == R.id.rb_wallet) {
                fragment = new WalletFragment();
            } else if (id == R.id.rb_store) {
                fragment = new StoreFragment();
            } else if (id == R.id.rb_order) {
                fragment = new OrderFragment();
            }
        }
        return fragment;
    }

    public void getAdSuccess(BannerBean data) {
        if (data != null) {
            HashMap<String, String> map = data.getDoc_url();
            List<BannerBean.ListBean> list = data.getList();
            if (list.size() > 0) {
                BannerBean.ListBean listBean = list.get(0);
                String imageUrl = map.get(listBean.getPath_id());
                String AdUrl = listBean.getUrl();
                RxView.visibility(getViewById(R.id.ll_ad)).call(true);
                GlideUtils.setRectImage(this,imageUrl, mIvPic);
                getViewById(R.id.iv_pic).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this, AdWebViewActivity.class);
                        intent.putExtra("url", AdUrl);
                        startActivity(intent);
                    }
                });
            }
        }
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.ll_ad:
                RxView.visibility(getViewById(R.id.ll_ad)).call(false);
                //红包
                beginRedPacket();
                break;
        }
    }

    private void beginRedPacket() {
        //生成随机金额
        Random random = new Random();
        double y = random.nextDouble() * (0.1 - 0.05) + 0.05;
        String redChange = String.valueOf(y).substring(0, 5);

        if (InfoProvider.getLoginStatus(this)){
            presenter.getRedpacket(redChange);
        }
    }

    private void showCloseRedPacket(String data, String gift_value) {
        RxView.visibility(getViewById(R.id.ll_ad)).call(false);
        RxView.visibility(getViewById(R.id.red_packet)).call(true);
        RxView.visibility(getViewById(R.id.rl_red_packet_close)).call(true);
        //点击关闭按钮 将红包隐藏
        getViewById(R.id.iv_red_packet_close_del).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxView.visibility(getViewById(R.id.red_packet)).call(false);
            }
        });

        ((Button)getViewById(R.id.iv_red_packet_to_open)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点开红包，随机生成金额
                showOpenRedPacket(data,gift_value);

            }
        });
    }

    private void showOpenRedPacket(String data, String gift_value) {
        //将红包放到零钱中
        presenter.openRedPacket(data,gift_value);
    }

    /**
     * 获取版本信息
     *
     * @param data
     */
    @Override
    public void getVersionSuccess(VersionInfo data) {
        if (data == null) {
            return;
        }
        int versionCode = data.getVersion_code();
        String downloadPath = data.getDownload_path();   //地址
        int currentVersionCode = SystemUtils.getVersionCode(MainActivity.this);
        if (currentVersionCode < versionCode) {     //版本更新
            mDialog = new UpdateDialog(this, new UpdateDialog.DialogClick() {
                @Override
                public void cancelClick() {
                    TipUtils.showToast(App.getInstance(), "当前版本不再支持,请更新到最新版本!");
                    finish();
                }

                @Override
                public void submitClick() {
                    if (!TextUtils.isEmpty(downloadPath)) {
                        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            doClick(downloadPath);
                        } else {
                            if (SystemUtils.isDownloadManagerAvailable(MainActivity.this)) {
                                Intent updateService = new Intent(MainActivity.this, UpdateService.class);
                                updateService.putExtra("download_url", downloadPath);
                                startService(updateService);
                                TipUtils.showToast(App.getInstance(),"下载中，请在通知栏查看!");
                                mDialog.stopProgressDialog();
                            } else {
                                doClick(downloadPath);
                                mDialog.stopProgressDialog();
                            }
                        }
                    } else {
                        TipUtils.showToast(App.getInstance(), "下载地址无效!");
                    }
                }
            });
            mDialog.setContent(data.getUpdate_content());
        }
    }

    /**
     * 获取版本升级信息。
     */
    @Override
    public void getUpdateInfoSuccess(UpdateBean updateBean) {
        if (updateBean == null) return;
        if (updateBean.getUpdate_status() != 1) return;
        if (updateBean.getIs_update() != 1) return;

        // appType != android(2)
        if (updateBean.getApp_type() != 2) {
            LogUtils.e("AppType != 2. Not for android update.");
            return;
        }

        int currentVerCode = SystemUtils.getVersionCode(MainActivity.this);
        int verCode = Integer.valueOf(updateBean.getVersion_no());
        if (currentVerCode >= verCode) {
            // Current version is latest version, no need to update.
            return;
        }

        String updateContent = updateBean.getUpdate_content();
        String downloadPath = updateBean.getDownload_path();
        String updateType = updateBean.getUpdate_type();

        if ("1".equals(updateType)) {
            showNormalUpdate(downloadPath, updateContent);

        } else if ("2".equals(updateType)) {
            showForcedUpdate(downloadPath, updateContent);
        }
    }

    // 普通更新
    private void showNormalUpdate(final String downloadPath, final String updateContent) {
        mDialog = new UpdateDialog(this, new UpdateDialog.DialogClick() {
            @Override
            public void cancelClick() {
                mDialog.stopProgressDialog();
            }

            @Override
            public void submitClick() {
                startDownload(downloadPath);
            }
        });
        mDialog.setContent(updateContent);
    }

    // 强制更新
    private void showForcedUpdate(final String downloadPath, final String updateContent) {
        mDialog = new UpdateDialog(this, new UpdateDialog.DialogClick() {
            @Override
            public void cancelClick() {
            }

            @Override
            public void submitClick() {
                startDownload(downloadPath);
            }
        });
        mDialog.setContent(updateContent);
        mDialog.disableCancelButton();
    }

    // 设置下载。
    private void startDownload(final String downloadPath) {
        if (EmptyUtil.isEmpty(downloadPath)) {
            TipUtils.showToast(App.getInstance(), "下载地址无效!");
            mDialog.stopProgressDialog();
            return;
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请权限
            doClick(downloadPath);
        } else {
            if (SystemUtils.isDownloadManagerAvailable(MainActivity.this)) {
                Intent updateService = new Intent(MainActivity.this, UpdateService.class);
                updateService.putExtra("download_url", downloadPath);
                startService(updateService);
                TipUtils.showToast(App.getInstance(),"下载中，请在通知栏查看!");
                mDialog.stopProgressDialog();
            } else {
                doClick(downloadPath);
            }
        }
    }

    /**
     * 获取默认商店
     *
     * @param collectedStores
     */
    @Override
    public void getDefaultStoresSuccess(CollectedStores collectedStores) {
        if (collectedStores.getList().size() == 1) {
            CollectedStores.Stores stores = collectedStores.getList().get(0);
            PreferenceUtils.putString(this, Constants.DEFAULT_STORE_ID, stores.getStores_id());
            PreferenceUtils.putString(this, Constants.DEFAULT_STORE_NAME, stores.getStores_name());
        } else {
            PreferenceUtils.putString(this, Constants.DEFAULT_STORE_ID, "");
            PreferenceUtils.putString(this, Constants.DEFAULT_STORE_NAME, "");
        }
    }

    //广告界面消失之后可以 显示红包
    @Override
    public void showRedPacketSucc(String data, String gift_value) {
        //detail_id = data;
        //如果登录就显示红包 并且没有领过红包
        //  if ( mRedMsg == null ){
        //如果登录了 就弹出红包 //显示红包
        showCloseRedPacket(data, gift_value);
        // }

    }

    //如果后台返回的是“您的一天只能领一次红包”那说明，不能再显示红包
    @Override
    public void showRedPacketFail(String msg) {
        mRedMsg = msg;
        //如果登录就显示红包 并且没有领过红包
        /* if ( mRedMsg == null ){
            //如果登录了 就弹出红包 //显示红包
            showCloseRedPacket();
        }*/

    }

    @Override
    public void openRedPacketSucc(String gift_value) {
        TipUtils.showToast(App.getInstance(),"领取红包成功！",3);
        RxView.visibility(getViewById(R.id.rl_red_packet_close)).call(false);
        RxView.visibility(getViewById(R.id.rl_red_packet_open)).call(true);

        //显示随机的红包金额
        ((TextView)getViewById(R.id.iv_red_packet_open_money)).setText(gift_value);
        //点击关闭
        getViewById(R.id.iv_red_packet_open_del).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxView.visibility(getViewById(R.id.red_packet)).call(false);
            }
        });

        getViewById(R.id.iv_red_click_change).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, WalletChangeActivity.class);
                startActivity(intent);
                //关闭红包界面
                RxView.visibility(getViewById(R.id.red_packet)).call(false);
            }
        });

    }

    @Override
    public void showFail(String msg) {
        TipUtils.showToast(App.getInstance(),msg,2);
    }


    @Override
    public void showError(String msg) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        Fragment fragment = null;

        Fragment currentFragment = fragmentManager.findFragmentByTag(fragmentTag);
        FragmentTransaction tr = fragmentManager.beginTransaction();
        if (tr != null) {
            tr.hide(currentFragment);
        }
        if (checkedId == R.id.rb_home) {
            fragment = fragmentManager.findFragmentByTag(HomeFragment.Tag);
            fragmentTag = HomeFragment.Tag;
            if (fragment != null) {
            } else {
                fragment = new HomeFragment();
            }
        } else if (checkedId == R.id.rb_store) {//店铺
            fragment = jumpToFragment(StoreFragment.Tag, R.id.rb_store);//登录成功商店页面
        } else if (checkedId == R.id.rb_wallet) {//钱包
            if (!InfoProvider.getLoginStatus(this) && !LoginActivity.mIsShow) {
                JumpUtil.jumpToLoginActivity(0, MainActivity.this, 0, CURRENT_FRAGMENT_TAG_WALLET);
                return;
            }
            fragment = jumpToFragment(WalletFragment.Tag, R.id.rb_wallet);//登录成功跳转到钱包界面

        } else if (checkedId == R.id.rb_order) {//订单
            if (!InfoProvider.getLoginStatus(this) && !LoginActivity.mIsShow) {
                JumpUtil.jumpToLoginActivity(0, MainActivity.this, 0, CURRENT_FRAGMENT_TAG_ORDER);
                return;
            }
            fragment = jumpToFragment(OrderFragment.Tag, R.id.rb_order);//登录成功跳转到订单界面
        } else if (checkedId == R.id.rb_mine) {//我
            if (!InfoProvider.getLoginStatus(this) && !LoginActivity.mIsShow) {
                JumpUtil.jumpToLoginActivity(0, MainActivity.this, 0, CURRENT_FRAGMENT_TAG_MINE);
                return;
            }
            fragment = jumpToFragment(MineFragment.Tag, R.id.rb_mine);//登录成功跳转到我的界面

        }
        if (fragment != null && fragment.isAdded()) {
            if (tr != null) {
                tr.show(fragment);
            }
        } else {
            if (tr != null) {
                tr.add(R.id.content, fragment, fragmentTag);
            }
        }
        if (tr != null) {
            if (this.isFinishing()) {   //判断Activity是否还存在
                return;
            }
            tr.addToBackStack(null);
            tr.commitAllowingStateLoss();
            getSupportFragmentManager().executePendingTransactions();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //友盟分享的QQ和微博的配置
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)//登录后的回调
        {
            if (data != null) {
                String strCurrentTag = data.getStringExtra(JumpUtil.INTENT_VALUE);
                if (strCurrentTag != null) {
                    if (strCurrentTag.equals(CURRENT_FRAGMENT_TAG_MINE)) {//我的
                        onCheckedChanged(rgHome, R.id.rb_mine);
                    } else if (strCurrentTag.equals(CURRENT_FRAGMENT_TAG_WALLET)) {//钱包
                        onCheckedChanged(rgHome, R.id.rb_wallet);
                    } else if (strCurrentTag == null || strCurrentTag.equals("")) {
                        ((RadioButton) findViewById(R.id.rb_home)).setChecked(true);
                        onCheckedChanged(rgHome, R.id.rb_home);
                    } else if (strCurrentTag.equals(CURRENT_FRAGMENT_TAG_STORE)) {//商店
                        onCheckedChanged(rgHome, R.id.rb_store);
                    } else if (strCurrentTag.equals(CURRENT_FRAGMENT_TAG_ORDER)) {//订单
                        onCheckedChanged(rgHome, R.id.rb_order);
                    }
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (!isFinishing()) {
            super.onBackPressed();
        }
        Intent setIntent = new Intent(Intent.ACTION_MAIN);
        setIntent.putExtra(INTENT_FLAG_SOURCE, true);
        setIntent.addCategory(Intent.CATEGORY_HOME);
        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(setIntent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            RxTimerUtils timerUtils = new RxTimerUtils();
            if (isExit == false) {
                isExit = true; // 准备退出
                TipUtils.showToast(App.getInstance(), "再按一下退出应用");
                timerUtils.interval(2000, number -> {
                    isExit = false; // 取消退出
                    timerUtils.cancel();
                });
            } else {
                this.finish();
                timerUtils.cancel();
            }
        }
        return false;
    }

    private void registerEvent() {
        RxBus.get().toFlowable(ExitEvent.class).subscribe(new Consumer<ExitEvent>() {
            @Override
            public void accept(ExitEvent exitEvent) throws Exception {
                if (exitEvent.mType == EXIT_HYPHENATE_EVENT) {
                    try {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(App.getInstance(), MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                ((RadioButton) findViewById(R.id.rb_home)).setChecked(true);
                                onCheckedChanged(rgHome, R.id.rb_home);
                                TipUtils.showToast(App.getInstance(),"当前账号在其他设备上登录");
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//
                }
            }
        });
        Disposable disposable = RxBus.get().toFlowable(CollectStoreEventBean.class).subscribe(new Consumer<CollectStoreEventBean>() {
            @Override
            public void accept(CollectStoreEventBean eventBean) throws Exception {
                if (eventBean.type.equals(Constants.COLLECT_MENU_COMFIRM)) {
                    presenter.getDefaultStores();
                }
            }
        });
        mCompositeDisposable.add(disposable);
        Disposable disposable1 =  RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean eventBean) throws Exception {
                if (eventBean.type == Constants.EVENT_TYPE_LOGIN_SUCCESS) {
                    presenter.getDefaultStores();
                }else if (eventBean.type == Constants.EVENT_TYPE_ADV_CLOSE_REDPACKET_SHOW){
                    //关闭广告，按条件是否显示红包
                    RxView.visibility(getViewById(R.id.ll_ad)).call(false);
                    RxView.visibility(getViewById(R.id.red_packet)).call(false);
                    //如果登录就显示红包 并且没有领过红包
                    beginRedPacket();
                }
            }
        });
        mCompositeDisposable.add(disposable1);
        Disposable subscribe = RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean.result == Constants.PAY_RESULT_SUCCESS | payResultBean.result == Constants.PAY_RESULT_FAIL_HUIGUO ) {

                    ((RadioButton) findViewById(R.id.rb_order)).setChecked(true);
                    onCheckedChanged(rgHome, R.id.rb_order);
                }
            }
        });
        mCompositeDisposable.add(subscribe);
    }

    public void doClick(final String downloadUrl) {
        try {
            Uri uri = Uri.parse(downloadUrl);
            Intent browserIntent = new Intent(Intent.ACTION_VIEW);
            browserIntent.setDataAndType(uri, "text/html");
            browserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            startActivity(browserIntent);
            MainActivity.this.finish();
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "请到腾讯应用宝更新最新安装包!", Toast.LENGTH_SHORT).show();
            MainActivity.this.finish();
        }
    }

}
